package com.csjbot.weedle_auto.app.main

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentTabHost
import android.support.v4.view.ViewPager
import android.support.v7.app.AlertDialog
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.csjbot.weedle_auto.R
import com.csjbot.weedle_auto.SerialServer.util.bean.SerialPortExceptionListener
import com.csjbot.weedle_auto.adapter.FragmentListener
import com.csjbot.weedle_auto.adapter.MyFragmentAdapter
import com.csjbot.weedle_auto.app.automatic.AutoMaticActivity
import com.csjbot.weedle_auto.base.BaseActivity
import com.csjbot.weedle_auto.fragment.AutomaticFramgent
import com.csjbot.weedle_auto.fragment.PrintFragment
import com.csjbot.weedle_auto.fragment.manual.ManualFragment
import com.csjbot.weedle_auto.serialport_util.SerialPortUtil
import com.csjbot.weedle_auto.view.CustomTitleBar
import com.csjbot.weedle_auto.view.CustomViewPagerView
import com.google.common.base.Preconditions.checkNotNull
import java.io.IOException
import java.security.InvalidParameterException
import java.util.*

class CsjBotActivity : BaseActivity(), ViewPager.OnPageChangeListener, View.OnClickListener, TabHost.OnTabChangeListener, SerialPortExceptionListener, FragmentListener, MainContract.view {
    override val resureID: Int
        get() = R.layout.activity_automation


    private var viewPager: CustomViewPagerView? = null
    private var mTabHost: FragmentTabHost? = null
    private var layout_view: LayoutInflater? = null
    private val title = arrayOf("手动调试", "自动调试", "打印报告")
    private val mViewList = ArrayList<View>()
    private val imageViewArray = intArrayOf(R.drawable.manual_select, R.drawable.auto_select, R.drawable.print_select)
    private val fragmentArray = arrayOf<Class<*>>(AutomaticFramgent::class.java, ManualFragment::class.java, PrintFragment::class.java)
    private var list: MutableList<Fragment>? = null
    private var customTitleBar: CustomTitleBar? = null
    private var adapter: MyFragmentAdapter? = null

    private var mpresenter: MainContract.presenter? = null

    private var bt = 0
    private var pt = ""


    private val datas = arrayOf("返回", "设置串口号")

    override fun initView() {
        SerialPortUtil.setSerialPortExceptionListener(this)
        //        ((BaseApplication) getApplication()).getSerialPortServer().openSerialPort(SerialPortConstants.BT, SerialPortConstants.path);
        viewPager = findViewById(R.id.viewpager) as CustomViewPagerView
        /*实现OnPageChangeListener接口,目的是监听Tab选项卡的变化，然后通知ViewPager适配器切换界面*/
        /*简单来说,是为了让ViewPager滑动的时候能够带着底部菜单联动*/
        viewPager!!.addOnPageChangeListener(this)//设置页面切换时的监听器
        layout_view = LayoutInflater.from(this)//加载布局管理器

        /*实例化FragmentTabHost对象并进行绑定*/
        mTabHost = findViewById(android.R.id.tabhost) as FragmentTabHost//绑定tahost
        mTabHost!!.setup(this, supportFragmentManager, R.id.viewpager)//绑定viewpager

        customTitleBar = findViewById(R.id.ct) as CustomTitleBar

        /*实现setOnTabChangedListener接口,目的是为监听界面切换），然后实现TabHost里面图片文字的选中状态切换*/
        /*简单来说,是为了当点击下面菜单时,上面的ViewPager能滑动到对应的Fragment*/
        mTabHost!!.setOnTabChangedListener(this)

        val count = title.size

        /*新建Tabspec选项卡并设置Tab菜单栏的内容和绑定对应的Fragment*/
        for (i in 0 until count) {
            // 给每个Tab按钮设置标签、图标和文字
            val tabSpec = mTabHost!!.newTabSpec(title[i])
                    .setIndicator(getTabItemView(i))
            // 将Tab按钮添加进Tab选项卡中，并绑定Fragment
            mTabHost!!.addTab(tabSpec, fragmentArray[i], null)
            mTabHost!!.tag = i
            mTabHost!!.tabWidget.getChildAt(i)//设置Tab被选中的时候颜色改变
        }

        customTitleBar!!.setOnTitleClickListener(object : CustomTitleBar.TitleOnClickListener {
            override fun onLeftClick() {}

            override fun onRightClick() {
                // TODO: 2016/5/17 构建一个popupwindow的布局
                val popupView = getLayoutInflater().inflate(R.layout.popupwindow, null)
                // TODO: 2016/5/17 为了演示效果，简单的设置了一些数据，实际中大家自己设置数据即可，相信大家都会。
                val lsvMore = popupView.findViewById(R.id.lsvMore) as ListView
                lsvMore.adapter = ArrayAdapter(this@CsjBotActivity, android.R.layout.simple_list_item_1, datas)

                // TODO: 2016/5/17 创建PopupWindow对象，指定宽度和高度
                val window = PopupWindow(popupView, 300, 400)
                // TODO: 2016/5/17 设置动画
                window.animationStyle = R.style.popup_window_anim
                // TODO: 2016/5/17 设置背景颜色
                window.setBackgroundDrawable(ColorDrawable(Color.parseColor("#F8F8F8")))
                // TODO: 2016/5/17 设置可以获取焦点
                window.isFocusable = true
                // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
                window.isOutsideTouchable = true
                // TODO：更新popupwindow的状态
                window.update()
                val windowManager = windowManager
                val dm = DisplayMetrics()
                windowManager.defaultDisplay.getMetrics(dm)
                val SCREENWIDTH = dm.widthPixels
                // TODO: 2016/5/17 以下拉的方式显示，并且可以设置显示的位置
                window.showAsDropDown(customTitleBar, SCREENWIDTH, 0)
                lsvMore.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
                    if (position == 1) {
                        dialogADDPort()
                    } else {
                        val intent = Intent(this@CsjBotActivity, AutoMaticActivity::class.java)
                        startActivity(intent)
                        this@CsjBotActivity.finish()
                    }
                }
            }
        })
        MainPresenter(this, this)
    }

    private fun dialogADDPort() {
        val dialog1 = AlertDialog.Builder(this)
        val contentView1 = LayoutInflater.from(this).inflate(R.layout.serial_dialog, null)
        dialog1.setView(contentView1)
        dialog1.setTitle("选择串口")

        val add = contentView1.findViewById(R.id.add) as Button
        val port = contentView1.findViewById(R.id.spinner1) as Spinner
        val path = contentView1.findViewById(R.id.spinner2) as Spinner

        port.setSelection(1, true)
        path.setSelection(1, true)
        /**
         * 默认选中
         */
        bt = Integer.parseInt(resources.getStringArray(R.array.btv)[1])
        pt = resources.getStringArray(R.array.path)[1]

        val alertDialog = dialog1.create()
        alertDialog.setCanceledOnTouchOutside(true)
        alertDialog.show()

        port.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                bt = Integer.parseInt(resources.getStringArray(R.array.btv)[position])
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }

        path.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                pt = resources.getStringArray(R.array.path)[position]
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }

        add.setOnClickListener {
            mpresenter!!.closeSerial()
            mpresenter!!.openSerialPort(pt, bt)
            //                ((BaseApplication) getApplication()).getSerialPortServer().openSerialPort(bt, pt);
            alertDialog.dismiss()
        }
    }

    private fun getTabItemView(i: Int): View {
        //将xml布局转换为view对象
        val view = layout_view!!.inflate(R.layout.tab_item_view, null)
        //利用view对象，找到布局中的组件,并设置内容，然后返回视图
        val mImageView = view
                .findViewById(R.id.imageview) as ImageView
        val mTextView = view.findViewById(R.id.textview) as TextView
        mImageView.setBackgroundResource(imageViewArray[i])
        mTextView.text = title[i]
        return view
    }


    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

    override fun onPageSelected(position: Int) {
        val widget = mTabHost!!.tabWidget
        val oldFocusability = widget.descendantFocusability
        widget.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
        mTabHost!!.currentTab = position
        widget.descendantFocusability = oldFocusability
    }

    override fun onPageScrollStateChanged(state: Int) {

    }

    override fun onClick(v: View) {
        for (i in title.indices) {
            val view = mViewList[i]
            view.setBackgroundColor(Color.WHITE)
            if (v.tag == title[i]) {
                view.setBackgroundColor(Color.YELLOW)
                viewPager!!.currentItem = i
            }
        }

    }

    override fun initPager() {
        list = ArrayList()
        val fragment1 = AutomaticFramgent()
        val fragment2 = ManualFragment()
        val fragment3 = PrintFragment()
        list!!.add(fragment2)
        list!!.add(fragment1)
        list!!.add(fragment3)
        adapter = MyFragmentAdapter(supportFragmentManager, list!!)
        //绑定Fragment适配器
        viewPager!!.adapter = adapter
        mTabHost!!.tabWidget.dividerDrawable = null
    }

    override fun onTabChanged(tabId: String) {
        val position = mTabHost!!.currentTab
        viewPager!!.currentItem = position//把选中的Tab的位置赋给适配器，让它控制页面切换
    }

    override fun ioException(e: IOException) {
        Toast.makeText(this, "串口未知错误请重新发送消息！", 2000).show()
    }

    override fun invalidException(e: InvalidParameterException) {
        Toast.makeText(this, "请配置你的端口！", 2000).show()
    }

    override fun securityException(e: SecurityException) {
        Toast.makeText(this, "请检查你的设备是否有串口！", 2000).show()
    }

    override fun otherException(error: Boolean) {
        Toast.makeText(this, "未知错误，请检查你的设备是否有串口！", 2000).show()
    }

    override fun onStart() {
        super.onStart()
        mpresenter!!.openSerialPort(pt, bt)
    }

    /**
     * 监听数据的刷新
     *
     * @param item
     */
    override fun onFragmentClickListener(item: Int) {
        adapter!!.update(item)
    }


    override fun setPresenter(presenter: MainContract.presenter) {
        mpresenter = checkNotNull(presenter)
    }

    override fun showPass() {}
}
